/**
 * Date: 2013-5-29
 * Copyright (C) 2013-2015 7Road. All rights reserved.
 */

package com.nirvana.utils;

import com.nirvana.config.PluginConfig;
import com.nirvana.data.DaoGenerateContext;
import com.nirvana.data.DbFieldInfo;
import com.nirvana.generate.OrmEntityGenerator;
import com.nirvana.type.DaoOption;

import java.util.List;

/**
 * @author jinjin.chen
 */
public class InterfaceCodeUtil {
    public static String generateInterfaceCode() {
        DaoGenerateContext context = OrmEntityGenerator.context;
        StringBuilder content = new StringBuilder();
        content.append("""
                package %s;
                
                import com.nirvana.database.IBaseDao;
                """.formatted(
                PluginConfig.getInstance().getDaoPackage()
        ));

        if (context.options.get(DaoOption.GET_ENTITY_LIST_BY_FIST_PRIMARY_KEY)) {
            content.append("import java.util.List;\n");
        }

        content.append("""
                import %s.%s;
                
                public interface %s extends IBaseDao<%s> {
                
                """.formatted(
                PluginConfig.getInstance().getEntityPackage(),
                context.entityName,
                CommonUtil.CreateInterfaceName(context.entityName),
                context.entityName
        ));

        if (context.options.get(DaoOption.GET_ENTITY_LIST_BY_FIST_PRIMARY_KEY)) {
            content.append(generateGetEntityByFirstPrimaryKey()).append("\n");
        }
        content.append("}\n");
        return content.toString();
    }

    private static String generateGetEntityByFirstPrimaryKey() {
        DaoGenerateContext context = OrmEntityGenerator.context;
        List<DbFieldInfo> primaryFields = context.primaryFields.stream().findFirst().stream().toList();
        return """
                    List<%s> get%sListBy%s(%s);
                """.formatted(
                context.entityName,
                context.entityName,
                CommonUtil.createPrimaryMethodName(primaryFields),
                CommonUtil.createPrimaryMethodParams(primaryFields)
        );
    }
}
